package com.ruoyi.app.framework.resolver;

import com.ruoyi.common.annotation.AuthUser;
import com.ruoyi.common.entity.VO.business.SysUserVO;
import lombok.NoArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于绑定@AuthUser的方法参数解析器
 *
 * @author lijiantao
 */
@NoArgsConstructor
public class AuthUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(SysUserVO.class) && parameter.hasParameterAnnotation(AuthUser.class);
    }

    @Override
    public SysUserVO resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SysUserVO user = new SysUserVO();
        Object userIdStr = request.getAttribute("userId");
        Object shopIdStr = request.getAttribute("shopId");
        if (userIdStr != null && shopIdStr != null) {
            user.setUserId(Long.valueOf(userIdStr.toString()));
            user.setShopId(Long.valueOf(shopIdStr.toString()));
        }
        return user;
    }
}